package com.gjy.droos.service.impl;

import com.gjy.droos.module.Order;
import com.gjy.droos.service.OrderFeeService;
import org.kie.api.definition.rule.Rule;
import org.kie.api.event.rule.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-01 14:30:11
 */
@Service
public class OrderFeeServiceImpl implements OrderFeeService {
    private static final Logger log = LoggerFactory.getLogger(OrderFeeServiceImpl.class);

    @Resource
    private KieContainer kieContainer;

    @Override
    public Order calculateFee(Order order) {
        KieSession kieSession = kieContainer.newKieSession();
        kieSession.addEventListener(new AgendaEventListener() {
            @Override
            public void matchCreated(MatchCreatedEvent matchCreatedEvent) {

            }

            @Override
            public void matchCancelled(MatchCancelledEvent matchCancelledEvent) {

            }

            @Override
            public void beforeMatchFired(BeforeMatchFiredEvent beforeMatchFiredEvent) {

            }

            @Override
            public void afterMatchFired(AfterMatchFiredEvent afterMatchFiredEvent) {
                Rule rule = afterMatchFiredEvent.getMatch().getRule();
                log.info("rule {},{}", rule.getName(), afterMatchFiredEvent.getMatch());
            }

            @Override
            public void agendaGroupPopped(AgendaGroupPoppedEvent agendaGroupPoppedEvent) {

            }

            @Override
            public void agendaGroupPushed(AgendaGroupPushedEvent agendaGroupPushedEvent) {

            }

            @Override
            public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent ruleFlowGroupActivatedEvent) {

            }

            @Override
            public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent ruleFlowGroupActivatedEvent) {

            }

            @Override
            public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent ruleFlowGroupDeactivatedEvent) {

            }

            @Override
            public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent ruleFlowGroupDeactivatedEvent) {

            }
        });
        kieSession.setGlobal("log", log);
        try {
            log.info("开始计算订单费用: {}", order.getOrderId());
            kieSession.insert(order);
            kieSession.fireAllRules();
            log.info("订单费用计算完成");
            return order;
        } finally {
            kieSession.dispose();
        }
    }

}
